function getSelected() {
    if(window.getSelection) {
        return window.getSelection();
    }
    else if(document.getSelection) {
        return document.getSelection();
    }
    else {
        var selection = document.selection && document.selection.createRange();
        if(selection.text) {
            return selection.text;
        }
        return false;
    }
    return false;
}

/*        
chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    alert(request.urls);
    if (request.urls){
      for (var i=0;i<request.urls;i++){
      	chrome.tabs.create({url:urls[i]});
      }
    }
    else
      sendResponse({}); // snub them.
  });
 */
var port;
//alert('create port');
function connectToTab(tabid){
    //alert('connect to tab ' + tabid);
    var newPort = chrome.tabs.connect(tabid,{
        name: "urls"
    });
    //alert('add listner to port');
    newPort.onMessage.addListener(function getResp(msg)
    {
        //alert('get the result to open in new tab');
        if (msg.urls != null && msg.urls.length > 0){
            for (var i=0;i<msg.urls.length;i++){
                chrome.tabs.create({
                    url:msg.urls[i]
                });
            }
        }
    });
    return newPort;
}

    var ports = new Array(500);
    var contexts = ["selection"];


var parent = chrome.contextMenus.create({
    "title": "Open All Links",
    "onclick": execute,
    "contexts": contexts
});

console.log('parent = ' + parent);


function execute(info, tab){
    var text = info.selectionText;
    var result;
    var pattern = /(https?:\/\/[^\s]+)/ig;
    result = text.match(pattern);
    //alert(result);
    if(result){
        for (var i=0;i<=result.length-1;i++){
            console.log(result[i]);
            //chrome.tabs.create({"url": result[i]});

        }


        console.log('send to content script at tab ' +tab.id);
        if (!ports[tab.id]) ports[tab.id] = connectToTab(tab.id);
        //alert('post Message');
        ports[tab.id].postMessage({
            urls: result
        });




        /*
		chrome.tabs.getSelected(null, function(tab)
			{
			  console.log('send to content script');
			  chrome.tabs.sendRequest(tab.id, {urls: result}, function(response)
			  {
			    console.log('populate tabs');
			    console.log(response.urls);
			  });
			});
         */
    }

}